package com.ruoyi.config;

/**
 * @author hlf
 * @createTime 2025/2/7 9:48
 * @description
 */
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(
        name = {"spring.rabbitmq.listener.simple.retry.enabled", "spring.rabbitmq.enabled"},
        havingValue = "true",
        matchIfMissing = true  // 如果没有配置这些属性，默认加载该配置
)public class ErrorMessageConfig {

    public static final String ERROR_QUEUE_NAME = "error_queue";
    public static final String ERROR_EXCHANGE_NAME = "error_direct_exchange";
    public static final String ERROR_ROUTING_KEY = "error_key";



    @Bean
    @Qualifier("errorQueue")
    public Queue errorQueue(){
        return QueueBuilder
                .durable(ERROR_QUEUE_NAME)
                .lazy() // 开启Lazy模式
                .build();
    }

    @Bean
    @Qualifier("errorExchange")
    public DirectExchange errorExchange() {
        return new DirectExchange(ERROR_EXCHANGE_NAME,true,false);
    }

    @Bean
    public Binding errorBinding(@Qualifier("errorQueue") Queue queue,  @Qualifier("errorExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ERROR_ROUTING_KEY);
    }

    @Bean
    public MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate){
        return new RepublishMessageRecoverer(rabbitTemplate, ERROR_EXCHANGE_NAME, ERROR_ROUTING_KEY);
    }
}